package cn.wizzer.app.crown.commons.util;


import cn.hutool.core.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

public class DecipherUtil {


    public static String encrypt(String key, String content) {

        try {

            // key转换
            DESKeySpec desKeySpec = new DESKeySpec(Base64.decode(key)); //实例化DES密钥规则
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); //实例化密钥工厂
            Key convertSecretKey = factory.generateSecret(desKeySpec); //生成密钥

            // 加密
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            return Base64.encode(cipher.doFinal(content.getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String key, String content) {

        try {

            // key转换
            DESKeySpec desKeySpec = new DESKeySpec(Base64.decode(key)); //实例化DES密钥规则
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); //实例化密钥工厂
            Key convertSecretKey = factory.generateSecret(desKeySpec); //生成密钥

            // 加密
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            // 解密
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            byte[] result = cipher.doFinal(Base64.decode(content));
            String val = new String(result);
            return val;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String generateKey () throws Exception {
        // 生成key//返回生成指定算法密钥的KeyGenerator对象
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        keyGenerator.init(56);//初始化此密钥生成器,使其具有确定的密钥大小
        SecretKey secretKey = keyGenerator.generateKey();//生成一个密钥
        byte[] bs = secretKey.getEncoded();
        return Base64.encode(bs);
    }
    public static void main(String[] args) throws Exception {
//        String key = generateKey();
        String key = "x54xgwQcTw4=";
        String en = encrypt(key, "subscribe=pagination");
        String de = decrypt(key,en);
//        System.out.println(key);
        System.out.println(en);
        System.out.println(de);
//        String s = "01mJ1Qdg3B3/vHv7+hhzVAOrP17536GB";
//        System.err.println(decrypt(key,s));
    }
}
